package com.cuz.series.linklist;

/**
 * 两两交换链表中的节点
 * https://leetcode.cn/problems/swap-nodes-in-pairs/
 */
public class 链表10两两交换链表中的节点 {
    public static void main(String[] args) {
        ListNode node = ListNode.of1(1, 2, 3, 4, 5);
        ListNode node1 = swapPairs1(node);
        node1.print();
    }

    public static ListNode swapPairs1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode preHead = new ListNode();
        preHead.next = head;
        ListNode slow = preHead;
        ListNode fast = head;
        ListNode tail = preHead;

        while (tail.next != null) {
            slow = slow.next;
            fast = slow.next;
            if (fast==null){
                break;
            }
            ListNode next = fast.next;
            tail.next = fast;
            fast.next = slow;
            slow.next = next;
            tail = slow;
        }

        return preHead.next;
    }
}
